﻿using System;
using System.Web;

/// <summary>
/// 全局异常处理类*
/// </summary>
/// <remarks>
/// 首先在Web.config中配置
///   <httpModules>
///     <add name="ErrorModule" type="ErrorModule"/>
///   </httpModules>
/// </remarks>
public class ErrorModule : IHttpModule
{
    #region IHttpModule 成员

    void IHttpModule.Dispose() { }

    void IHttpModule.Init(HttpApplication context)
    {
        context.Error += new System.EventHandler(context_Error);
    }

    #endregion

    void context_Error(object sender, System.EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        Exception ex = context.Server.GetLastError();
        if (ex == null)
            return;
        String errorCode = Guid.NewGuid().ToString();
        String errorMsg = ex.InnerException == null ? ex.GetBaseException().Message : ex.InnerException.Message;
        //首先在Global.asax的Application_Start方法中读取Log4Net的配置文件		
        log4net.LogManager.GetLogger(GetType()).Error(BuildErrorString(errorCode, context));
        context.Server.ClearError();
        ShowError(errorCode, errorMsg, context);
    }

    private String BuildErrorString(string errorCode, HttpContext context)
    {
        Exception ex = context.Server.GetLastError();
        System.Text.StringBuilder errorStr = new System.Text.StringBuilder();
        if (ex != null)
        {
            errorStr.Append("{ErrorCode:");
            errorStr.Append(errorCode);
            errorStr.Append(",ErrorPage:");
            errorStr.Append(context.Request.Url.ToString());
            errorStr.Append(",ErrorMsg:");
            errorStr.Append(ex.GetBaseException().Message);
            errorStr.Append(",StackTrace:");
            errorStr.Append(ex.StackTrace);
            if (ex.InnerException != null)
            {
                errorStr.Append(",InnerErrorMsg:");
                errorStr.Append(ex.InnerException.Message);
                errorStr.Append(",InnerStackTrace:");
                errorStr.Append(ex.InnerException.StackTrace);
            }
            errorStr.Append("}");
        }
        return errorStr.ToString();
    }

    private void ShowError(string errorCode, string errorMsg, HttpContext context)
    {
        HttpResponse response = context.Response;
        System.Text.StringBuilder errorPage = new System.Text.StringBuilder();
        if (Tools.CheckAgent())
        {
            errorPage.Append("<!DOCTYPE html><html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/><meta name='viewport' content='width=device-width, initial-scale=1'/></head><body>");
        }
        else
        {
            errorPage.Append("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/></head><body>");    
        }        
        errorPage.Append("<div style='margin:5px;border:1px solid #DDCCDD;padding:5px;'><p><strong>错误代码：</strong>");
        errorPage.Append(errorCode);
        errorPage.Append("</p><p><strong>错误消息：</strong>");
        errorPage.Append(errorMsg);
        errorPage.Append("</p><p><strong>系统异常请重试,若重复出现请联系系统管理员！</strong></p></div></body></html>");
        response.Write(errorPage.ToString());
        response.End();
        response.Clear();
    }
}
